package com.cjkj.system.service.impl;

import com.cjkj.common.core.constant.*;
import com.cjkj.common.core.domain.PatVisitIntervalData;
import com.cjkj.common.core.domain.R;
import com.cjkj.common.core.domain.runset.RunSetParam;
import com.cjkj.common.core.domain.runset.SendCommandReq;
import com.cjkj.common.core.domain.runset.TimeSetDto;
import com.cjkj.common.core.exception.ServiceException;
import com.cjkj.common.core.utils.DateUtils;
import com.cjkj.common.core.utils.RunModeSetUtil;
import com.cjkj.common.core.utils.StringUtils;
import com.cjkj.common.core.utils.bean.BeanUtils;
import com.cjkj.common.core.utils.uuid.SnowflakeIdGenerator;
import com.cjkj.common.core.web.domain.AjaxResult;
import com.cjkj.common.security.utils.SecurityUtils;
import com.cjkj.system.api.RemoteTJ01DataService;
import com.cjkj.system.api.RemoteTJ02DataService;
import com.cjkj.system.api.RemoteTJ03DataService;
import com.cjkj.system.api.RemoteTJ03Service;
import com.cjkj.system.api.domain.APIMonitorPadData;
import com.cjkj.system.api.domain.APISmartBraceletData;
import com.cjkj.system.api.domain.APITJ03RealTimeData;
import com.cjkj.system.api.domain.THospitalUser;
import com.cjkj.system.api.domain.request.LatestDatasReq;
import com.cjkj.system.api.domain.request.PatientEquipmentRTDReq;
import com.cjkj.system.api.domain.request.RecordsReq;
import com.cjkj.system.domain.*;
import com.cjkj.system.domain.dto.DiagnosisReq;
import com.cjkj.system.domain.dto.PatVisitReq;
import com.cjkj.system.domain.dto.PatientEditInfoReq;
import com.cjkj.system.domain.dto.VisitRecordReq;
import com.cjkj.system.domain.vo.*;
import com.cjkj.system.mapper.*;
import com.cjkj.system.service.ITPatVisitService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 患者就诊记录Service业务层处理
 * 
 * @author cjkj
 * @date 2024-08-30
 */
@Service
public class TPatVisitServiceImpl implements ITPatVisitService 
{
    @Resource
    private TPatVisitMapper tPatVisitMapper;

    @Resource
    private TPatIndexMapper tIndexMapper;

    @Resource
    private THospitalEquipmentMapper hospitalEquipmentMapper;

    @Resource
    private TEquipmentUsageRecordsMapper equipmentUsageRecordsMapper;

    @Resource
    private THospitalInfoMapper tHospitalInfoMapper;

    @Resource
    private RemoteTJ01DataService remoteTJ01DataService;

    @Resource
    private RemoteTJ02DataService remoteTJ02DataService;

    @Resource
    private RemoteTJ03DataService remoteTJ03DataService;

    @Resource
    private RemoteTJ03Service remoteTJ03Service;

    @Resource
    private TPatVisitSetMapper tPatVisitSetMapper;

    /**
     * 查询患者就诊记录列表
     *
     * @param req 查询条件
     * @return 患者就诊记录
     */
    @Override
    public List<PatVisitListVo> getTPatVisitList(PatVisitReq req)
    {
        return tPatVisitMapper.selectTPatVisitList(req);
    }

    @Override
    public List<PatVisitSimpleVo> getVisitList(PatVisitReq req) {
        return tPatVisitMapper.selectVisitSimpleList(req);
    }

    @Override
    public List<PatVisitListVo> getAllList(PatVisitReq req) {
        return tPatVisitMapper.selectAllList(req);
    }

    /**
     * 新增患者就诊记录
     *
     * 1.若就诊地在医院，判断床位是否被占用
     * 2.将患者基本信息存入pat_index表中，生成patient_id
     * 3.将患者本次就诊的信息写入pat_visit表中，生成visit_no
     * 4.将患者使用的设备信息，存入equipment_usage_records表中
     * 5.修改医院设备表hospital_equipment的设备状态，改为使用中
     * @param req 患者就诊信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(PatientEditInfoReq req)
    {
        // 设置参数信息
        setReqParamInfo(req);
        String dataType = req.getDataType();

        // 判断床位号是否占用
        bedIsOccupy(req);

        // 将患者基本信息存入pat_index表中
        Long patientId = saveTPatIndex(req);

        // 将患者本次就诊的信息写入pat_visit表中
        TPatVisit visitTemp = tPatVisitMapper.selectByPatientIdAndHospitalId(patientId, req.getHospitalId(), PatVisitStatusConstants.VISIT_STATUS_UNDERWAY, dataType);
        if (visitTemp != null) {
            throw new ServiceException("该患者有未结束的就诊");
        }

        // 多参开单时，查询该医院预设的开单时长
        if(EquipmentConstants.EQUIPMENT_TYPE_SMART_BRACELET_TYPE.equals(dataType)) {
            THospitalInfo tHospitalInfo = tHospitalInfoMapper.selectTHospitalInfoByHospitalId(req.getHospitalId());
            req.setRentalDays(tHospitalInfo == null ? 24 : tHospitalInfo.getBindDuration());
        }

        TPatVisit visit = new TPatVisit();
        BeanUtils.copyBeanProp(visit, req);
        visit.setVisitNo(SnowflakeIdGenerator.getInstance().nextId());
        visit.setPatientId(patientId);
        visit.setVisitStatus(PatVisitStatusConstants.VISIT_STATUS_UNDERWAY);

        // 心电血压监测仪需要保存运行设置项目
        if(EquipmentConstants.EQUIPMENT_TYPE_EB_TYPE.equals(dataType)) {
            req.setVisitNo(visit.getVisitNo());
            // 保存设置
            RunSetParam runSetParam = saveModeSet(req);
            // 获取最晚结束的时间作为整个就诊数据的预计结束时间
            if(runSetParam != null) {
                Long theLatestTime = RunModeSetUtil.getTheLatestTime(runSetParam);
                visit.setOutTime(new Date(theLatestTime));
            }
        }

        int visitFlag = tPatVisitMapper.insertTPatVisit(visit);
        if (visitFlag < 1) {
            throw new ServiceException("登记患者基本信息出错");
        }

        // 校验设备使用剩余次数（睡眠监测垫需要）
        if(EquipmentConstants.EQUIPMENT_TYPE_MONITOR_PAD_TYPE.equals(dataType)) {
            isAdequate(req);
        }

        // 更新设备使用记录
        req.setVisitNo(visit.getVisitNo());
        createEquipmentUseRecord(req, null);

        // 更新医院设备使用状态
        updateHospitalEquipmentStatus(req.getEquipmentId(), EquipmentConstants.H_EQUIPMENT_USE_FLAG_INUSE, req.getUpdateBy(), req.getUpdateTime());

        return 1;
    }

    RunSetParam saveModeSet(PatientEditInfoReq req){
        // 1-动态血压模式，2-动态心电模式，3-动态血压+动态心电模式，4-普通血压计模式
        String mode = req.getMode();
        if(StringUtils.isBlank(mode) && "4".equals(mode)) {
            return null;
        }
        Long visitNo = req.getVisitNo();

        TPatVisitSet visitSet = new TPatVisitSet();
        visitSet.setVisitNo(visitNo);
        if("2".equals(mode) || "3".equals(mode)) {
            // 动态心电
            TimeSetDto ecgTime = req.getEcgTime();
            visitSet.setEcgTimeStart(ecgTime.getStart());
            visitSet.setEcgTimeEnd(ecgTime.getEnd());
        }

        if("1".equals(mode) || "3".equals(mode)) {
            TimeSetDto bpPlanDaytime = req.getBpPlanDaytime();
            TimeSetDto bpPlanNight = req.getBpPlanNight();

            visitSet.setBpPlan(req.getBpPlan());
            visitSet.setBpDayStartTime(bpPlanDaytime.getStart());
            visitSet.setBpDayEndTime(bpPlanDaytime.getEnd());
            visitSet.setBpDayReminderFlag(bpPlanDaytime.getReminder());
            visitSet.setBpDayIntervalTimes(bpPlanDaytime.getInterval());

            visitSet.setBpNightStartTime(bpPlanNight.getStart());
            visitSet.setBpNightEndTime(bpPlanNight.getEnd());
            visitSet.setBpNightReminderFlag(bpPlanNight.getReminder());
            visitSet.setBpNightIntervalTimes(bpPlanNight.getInterval());
        }
        // 先删除旧配置
        tPatVisitSetMapper.deleteTPatVisitSetByVisitNo(visitNo);
        // 保存设置
        tPatVisitSetMapper.insertTPatVisitSet(visitSet);

        // 发送命令
        SendCommandReq commandReq = new SendCommandReq();
        BeanUtils.copyBeanProp(commandReq, req);
        RunSetParam setInfo = RunModeSetUtil.getSetInfo(commandReq);
        remoteTJ03Service.sendCommand(req.getEquipmentNo(), setInfo, SecurityConstants.INNER);

        return setInfo;
    }

    /**
     * 修改患者就诊记录
     *
     * @param req 患者就诊信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(PatientEditInfoReq req)
    {
        Long visitNo = req.getVisitNo();
        // 修改就诊信息
        TPatVisit tPatVisit = tPatVisitMapper.selectTPatVisitByVisitNo(visitNo);
        if (tPatVisit == null) {
            throw new ServiceException("未查询到该患者就诊信息！");
        }
        // 设置参数信息
        setReqParamInfo(req);
        // 判断床位号是否占用
        bedIsOccupy(req);
        // 保存患者基本信息
        Long patientId = saveTPatIndex(req);

        TPatVisit visit = new TPatVisit();
        BeanUtils.copyBeanProp(visit, req);
        visit.setVisitNo(visitNo);
        visit.setPatientId(patientId);
        visit.setVisitStatus(PatVisitStatusConstants.VISIT_STATUS_UNDERWAY);

        // 心电血压监测仪需要保存运行设置项目
        if(PatVisitStatusConstants.VISIT_STATUS_UNDERWAY.equals(tPatVisit.getVisitStatus())
                && EquipmentConstants.EQUIPMENT_TYPE_EB_TYPE.equals(req.getDataType())) {
            // 保存设置
            RunSetParam runSetParam = saveModeSet(req);
            // 获取最晚结束的时间作为整个就诊数据的预计结束时间
            if(runSetParam != null) {
                Long theLatestTime = RunModeSetUtil.getTheLatestTime(runSetParam);
                visit.setOutTime(new Date(theLatestTime));
            }
        }

        int visitFlag = tPatVisitMapper.updateTPatVisit(visit);
        if (visitFlag < 1) {
            throw new ServiceException("修改患者基本信息出错");
        }

        // 就诊中的患者才能修改设备
        if (PatVisitStatusConstants.VISIT_STATUS_UNDERWAY.equals(tPatVisit.getVisitStatus())) {
            // 校验设备使用剩余次数（睡眠监测垫需要）
            if(EquipmentConstants.EQUIPMENT_TYPE_MONITOR_PAD_TYPE.equals(req.getDataType())) {
                isAdequate(req);
            }

            /* 设备使用记录 */
            // 删除旧的设备使用记录
            TEquipmentUsageRecords oldUsage = deleteEquipmentUseRecord(req);
            // 添加新的设备使用记录
            req.setVisitNo(visit.getVisitNo());
            createEquipmentUseRecord(req, oldUsage.getUseStatus());

            /* 更新医院设备状态 */
            // 修改旧的设备为未使用
            updateHospitalEquipmentStatus(oldUsage.getEquipmentId(), EquipmentConstants.H_EQUIPMENT_USE_FLAG_FREE, req.getUpdateBy(), req.getUpdateTime());
            // 修改新的设备为使用中
            updateHospitalEquipmentStatus(req.getEquipmentId(), EquipmentConstants.H_EQUIPMENT_USE_FLAG_INUSE, req.getUpdateBy(), req.getUpdateTime());
        }

        return 1;
    }

    /**
     * 设置参数
     * @param req
     */
    private void setReqParamInfo(PatientEditInfoReq req) {
        THospitalUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        Date nowDate = DateUtils.getNowDate();
        String userName = sysUser.getUserName();
        String hospitalId = sysUser.getHospitalId();
        String deptId = sysUser.getDeptId();

        req.setHospitalId(hospitalId);
        req.setDeptId(deptId);
        req.setDoctorId(sysUser.getUserId());
        req.setVisitTime(nowDate);
        req.setCreateBy(userName);
        req.setCreateTime(nowDate);
        req.setUpdateBy(userName);
        req.setUpdateTime(nowDate);
    }

    /**
     * 睡眠监测垫判断剩余可用次数是否充足
     * @param req
     */
    private void isAdequate(PatientEditInfoReq req){
        String equipmentNo = req.getEquipmentNo();
        String equipmentId = req.getEquipmentId();
        THospitalEquipment tHospitalEquipment = hospitalEquipmentMapper.selectByEquipmentId(equipmentId);
        if(EquipmentConstants.H_EQUIPMENT_USE_FLAG_INUSE.equals(tHospitalEquipment.getUseFlag())
                && ! tHospitalEquipment.getEquipmentId().equals(equipmentId)
        ) {
            throw new ServiceException("设备"+equipmentNo+"正在使用中！");
        }

        // 分配次数
        Integer usageFrequency = tHospitalEquipment.getUsageFrequency();
        // 已使用次数
        Integer useTimes = tHospitalEquipment.getUseTimes();
        // 剩余次数
        int sycs = usageFrequency - useTimes;
        if (sycs <= 0 || sycs < req.getRentalDays()) {
            throw new ServiceException("设备"+equipmentNo+"剩余使用次数不足，请更换其他设备！");
        }
    }

    /**
     * 判断床位是否占用
     * @param req
     */
    private void bedIsOccupy (PatientEditInfoReq req) {
        String bedNo = req.getBedNo();
        if (PatVisitStatusConstants.VISIT_LOCATION_HOSPITAL.equals(req.getPlace()) && StringUtils.isNotBlank(bedNo)) {
            TPatVisit param = new TPatVisit();
            param.setHospitalId(req.getHospitalId());
            param.setDeptId(req.getDeptId());
            param.setDataType(req.getDataType());
            param.setBedNo(bedNo);
            param.setVisitStatus(PatVisitStatusConstants.VISIT_STATUS_UNDERWAY);
            param.setVisitNo(req.getVisitNo());
            List<TPatVisit> tPatVisits = tPatVisitMapper.selectList(param);
            if(! tPatVisits.isEmpty()) {
                throw new ServiceException("当前床位已被占用！");
            }
        }
    }

    /**
     * 保存患者基础信息
     * @param req
     * @return
     */
    Long saveTPatIndex(PatientEditInfoReq req) {

        String hospitalId = req.getHospitalId();

        TPatIndex patIndex = new TPatIndex();
        patIndex.setPatientName(req.getPatientName());
        patIndex.setIdentityNumber(req.getIdentityNumber());
        patIndex.setGender(req.getGender());
        patIndex.setBirthday(req.getBirthday());
        patIndex.setPhone(req.getPhone());
        patIndex.setProvince(req.getProvince());
        patIndex.setCity(req.getCity());
        patIndex.setDistrict(req.getDistrict());
        patIndex.setAddress(req.getAddress());
        patIndex.setHospitalId(hospitalId);

        TPatIndex indexTemp = tIndexMapper.selectByIdNoAndHospitalId(patIndex.getIdentityNumber(), hospitalId);
        int indexFlag = 0;
        if (indexTemp == null) {
            patIndex.setPatientId(SnowflakeIdGenerator.getInstance().nextId());
            patIndex.setCreateBy(req.getUpdateBy());
            patIndex.setCreateTime(req.getUpdateTime());
            patIndex.setUpdateBy(req.getUpdateBy());
            patIndex.setUpdateTime(req.getUpdateTime());
            indexFlag = tIndexMapper.insertTPatIndex(patIndex);
        } else {
            patIndex.setUpdateBy(req.getUpdateBy());
            patIndex.setUpdateTime(req.getUpdateTime());
            patIndex.setPatientId(indexTemp.getPatientId());
            indexFlag = tIndexMapper.updateTPatIndex(patIndex);
        }
        if (indexFlag < 1) {
            throw new ServiceException("登记患者基本信息出错");
        }

        return patIndex.getPatientId();
    }

    /**
     * 删除设备使用记录
     * @param req
     */
    TEquipmentUsageRecords deleteEquipmentUseRecord(PatientEditInfoReq req) {

        TEquipmentUsageRecords tEquipmentUsageRecords = equipmentUsageRecordsMapper.selectByVisitNo(req.getVisitNo(), EquipmentConstants.EQUIPMENT_USE_FLAG_INUSE);
        tEquipmentUsageRecords.setDelFlag("2");
        tEquipmentUsageRecords.setUseFlag(EquipmentConstants.EQUIPMENT_USE_FLAG_END);
        tEquipmentUsageRecords.setEndTime(req.getUpdateTime());
        tEquipmentUsageRecords.setUpdateBy(req.getUpdateBy());
        tEquipmentUsageRecords.setUpdateTime(req.getUpdateTime());

        if (equipmentUsageRecordsMapper.updateTEquipmentUsageRecords(tEquipmentUsageRecords) < 1) {
            throw new ServiceException("分配设备出错！");
        }

        return tEquipmentUsageRecords;
    }
    /**
     * 创建设备使用记录
     */
    void createEquipmentUseRecord(PatientEditInfoReq req, String oldUsageStatus) {
        TEquipmentUsageRecords record = new TEquipmentUsageRecords();
        BeanUtils.copyBeanProp(record, req);
        record.setEquipmentType(req.getDataType());
        record.setUseFlag(EquipmentConstants.EQUIPMENT_USE_FLAG_INUSE);
        record.setStartTime(req.getVisitTime());

        // 旧记录的设备使用状态
        if(StringUtils.isNotBlank(oldUsageStatus)) {
            record.setUseStatus(oldUsageStatus);
        }

        int i = equipmentUsageRecordsMapper.insertTEquipmentUsageRecords(record);
        if (i < 1) {
            throw new ServiceException("分配设备出错！");
        }
    }

    /**
     * 更新医院设备使用情况
     */
    void updateHospitalEquipmentStatus(String equipmentId, String useFlag, String opName, Date opTime) {
        THospitalEquipment equipment = new THospitalEquipment();
        equipment.setEquipmentId(equipmentId);
        equipment.setUseFlag(useFlag);
        equipment.setUpdateBy(opName);
        equipment.setUpdateTime(opTime);
        int flag = hospitalEquipmentMapper.updateEquipmentUseStatus(equipment);
        if (flag < 1) {
            throw new ServiceException("更新设备使用状态失败");
        }
    }

    @Override
    public PatientEditInfoReq getInfo(Long visitNo) {
        PatientEditInfoReq patientEditInfoReq = tPatVisitMapper.selectPatientEditInfoByVisitNo(visitNo);
        if(patientEditInfoReq == null) {
            throw new ServiceException("未找到该患者信息");
        }

        // 1-动态血压模式，2-动态心电模式，3-动态血压+动态心电模式，4-普通血压计模式
        String mode = patientEditInfoReq.getMode();
        if(StringUtils.isNotBlank(mode) && !"4".equals(mode)) {
            TPatVisitSet tPatVisitSet = tPatVisitSetMapper.selectTPatVisitSetByVisitNo(visitNo);
            if(tPatVisitSet != null) {
                // 动态血压数据
                if("1".equals(mode) || "3".equals(mode)) {
                    patientEditInfoReq.setBpPlan(tPatVisitSet.getBpPlan());
                    patientEditInfoReq.setBpPlanDaytime(new TimeSetDto(tPatVisitSet.getBpDayStartTime(), tPatVisitSet.getBpDayEndTime(), tPatVisitSet.getBpDayReminderFlag(), tPatVisitSet.getBpDayIntervalTimes()));
                    patientEditInfoReq.setBpPlanNight(new TimeSetDto(tPatVisitSet.getBpNightStartTime(), tPatVisitSet.getBpNightEndTime(), tPatVisitSet.getBpNightReminderFlag(), tPatVisitSet.getBpNightIntervalTimes()));
                }

                // 动态心电数据
                if("2".equals(mode) || "3".equals(mode)) {
                    TimeSetDto ecgTimeSet = new TimeSetDto();
                    ecgTimeSet.setStart(tPatVisitSet.getEcgTimeStart());
                    ecgTimeSet.setEnd(tPatVisitSet.getEcgTimeEnd());
                    patientEditInfoReq.setEcgTime(ecgTimeSet);
                }
            }
        }
        return patientEditInfoReq;
    }

    @Override
    public PatientDetailInfoVo getDetailInfo(Long visitNo) {
        PatientDetailInfoVo detailInfo = tPatVisitMapper.getDetailInfo(visitNo);
        if(detailInfo == null) {
            throw new ServiceException("未找到该患者信息");
        }
        if(! EquipmentConstants.EQUIPMENT_TYPE_EB_TYPE.equals(detailInfo.getDataType())) {
            PatVisitIntervalData intervalTime = DateUtils.getIntervalTime(detailInfo.getVisitTime(), detailInfo.getRentalDays(), detailInfo.getOutTime(), detailInfo.getDataType());
            detailInfo.setOutTime(intervalTime.getOutTime());
        } else {
            TPatVisitSet tPatVisitSet = tPatVisitSetMapper.selectTPatVisitSetByVisitNo(visitNo);
            SendCommandReq commandReq = getSendCommandReq(detailInfo, tPatVisitSet);
            detailInfo.setRunSet(RunModeSetUtil.getSetInfo(commandReq));
        }
        return detailInfo;
    }

    private static SendCommandReq getSendCommandReq(PatientDetailInfoVo detailInfo, TPatVisitSet tPatVisitSet) {
        SendCommandReq commandReq = new SendCommandReq();
        commandReq.setEquipmentNo(detailInfo.getEquipmentNo());
        commandReq.setVisitTime(detailInfo.getVisitTime());
        commandReq.setMode(detailInfo.getMode());
        commandReq.setBpPlan(tPatVisitSet.getBpPlan());
        commandReq.setBpPlanDaytime(new TimeSetDto(tPatVisitSet.getBpDayStartTime(), tPatVisitSet.getBpDayEndTime(), tPatVisitSet.getBpDayReminderFlag(), tPatVisitSet.getBpDayIntervalTimes()));
        commandReq.setBpPlanNight(new TimeSetDto(tPatVisitSet.getBpNightStartTime(), tPatVisitSet.getBpNightEndTime(), tPatVisitSet.getBpNightReminderFlag(), tPatVisitSet.getBpNightIntervalTimes()));
        commandReq.setEcgTime(new TimeSetDto(tPatVisitSet.getEcgTimeStart(), tPatVisitSet.getEcgTimeEnd()));
        return commandReq;
    }

    /**
     * 更新就诊记录表，将就诊状态标记为结束，更新出院时间  t_pat_visit
     * 更新设备使用记录表，将记录标记为结束   t_equipment_usage_records
     * 更新医院设备使用状态，将设备状态标记为空闲、记录使用次数  t_hospital_equipment
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void leaveHospital(Long visitNo) {
        Date nowDate = DateUtils.getNowDate();
        String opName = SecurityUtils.getUsername();

        // 就诊状态标记为结束，更新出院时间
        TPatVisit patVisit = updateVisitStauts(visitNo, nowDate, opName);
        // 设备使用记录表标记为未使用
        String equipmentId = updateEquipmentUseRecord(visitNo, nowDate, opName);
        // 更新医院设备使用状态，将设备状态标记为空闲
        updateHospitalEquipmentStatus(equipmentId, patVisit.getVisitTime(), patVisit.getRentalDays(), nowDate, opName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchLeaveHospital(String visitNos) {
        if(StringUtils.isBlank(visitNos)){
            throw new ServiceException("就诊号不能为空！");
        }
        Date nowDate = DateUtils.getNowDate();
        String opName = SecurityUtils.getUsername();
        String[] visitNoArray = visitNos.split(",");
        for (String visitNoStr: visitNoArray) {
            Long visitNo = Long.valueOf(visitNoStr);

            // 就诊状态标记为结束，更新出院时间
            TPatVisit patVisit = updateVisitStauts(visitNo, nowDate, opName);
            // 设备使用记录表标记为未使用
            String equipmentId = updateEquipmentUseRecord(visitNo, nowDate, opName);
            // 更新医院设备使用状态，将设备状态标记为空闲
            updateHospitalEquipmentStatus(equipmentId, patVisit.getVisitTime(), patVisit.getRentalDays(), nowDate, opName);
        }
    }

    private TPatVisit updateVisitStauts(Long visitNo, Date nowDate, String opName) {
        TPatVisit patVisit = tPatVisitMapper.selectTPatVisitByVisitNo(visitNo);
        if (patVisit == null) {
            throw new ServiceException("患者出院，未查询到患者信息");
        }

        patVisit.setVisitStatus(PatVisitStatusConstants.VISIT_STATUS_END);
        patVisit.setOutTime(nowDate);
        patVisit.setUpdateBy(opName);
        patVisit.setUpdateTime(nowDate);
        int count = tPatVisitMapper.updateTPatVisitStatus(patVisit);
        if (count < 1) {
            throw new ServiceException("患者出院，更新就诊信息出错！");
        }
        return patVisit;
    }

    private String updateEquipmentUseRecord(Long visitNo, Date nowDate, String opName){
        TEquipmentUsageRecords tEquipmentUsageRecords = equipmentUsageRecordsMapper.selectByVisitNo(visitNo, EquipmentConstants.EQUIPMENT_USE_FLAG_INUSE);
        if (tEquipmentUsageRecords == null) {
            throw new ServiceException("未找到关联的设备使用记录！");
        }
        tEquipmentUsageRecords.setUseFlag(EquipmentConstants.EQUIPMENT_RECORD_STATUS_END);
        tEquipmentUsageRecords.setEndTime(nowDate);
        tEquipmentUsageRecords.setUpdateBy(opName);
        tEquipmentUsageRecords.setUpdateTime(nowDate);
        int i = equipmentUsageRecordsMapper.updateTEquipmentUsageRecords(tEquipmentUsageRecords);
        if (i < 1) {
            throw new ServiceException("修改设备使用记录失败！");
        }

        return tEquipmentUsageRecords.getEquipmentId();
    }

    private void updateHospitalEquipmentStatus(String equipmentId, Date visitTime, Integer rentalDays, Date nowDate, String opName){
        THospitalEquipment tHospitalEquipment = hospitalEquipmentMapper.selectByEquipmentId(equipmentId);
        if (tHospitalEquipment == null) {
            throw new ServiceException("未找到关联的设备信息！");
        }
        tHospitalEquipment.setUseFlag(EquipmentConstants.H_EQUIPMENT_USE_FLAG_FREE);
        tHospitalEquipment.setUpdateBy(opName);
        tHospitalEquipment.setUpdateTime(nowDate);

        // 修改设备使用次数
        // 如果出院时间距离开单时间大于一小时，才减次数
        if(nowDate.getTime() - visitTime.getTime() > (60 * 60 * 1000)) {
            int days = 0;
            // 获取开单时间到当前出院时间的所有区间日期
            List<Date> allDatesInTheDateRange = DateUtils.getAllDatesInTheDateRange(visitTime, nowDate);
            for (int i = 0; i < allDatesInTheDateRange.size() - 1; i ++) {
                Date start = allDatesInTheDateRange.get(i);
                Date end = allDatesInTheDateRange.get(i + 1);
                long l = end.getTime() - start.getTime();
                if(l > (60 * 60 * 1000)) {
                    days += 1;
                }
            }
            // 实际租用天数
            rentalDays = Math.min(rentalDays, days);

            Integer oldTimes = tHospitalEquipment.getUseTimes();
            tHospitalEquipment.setUseTimes((oldTimes == null ? 0 : oldTimes) + rentalDays);
        }
        int i = hospitalEquipmentMapper.updateTHospitalEquipment(tHospitalEquipment);
        if (i < 1) {
            throw new ServiceException("修改设备状态失败！");
        }
    }

    /**
     * 删除患者就诊记录信息
     * 
     * @param visitNo 患者就诊记录主键
     * @return 结果
     */
    @Override
    public int deleteTPatVisitByVisitNo(Long visitNo)
    {
        return tPatVisitMapper.deleteTPatVisitByVisitNo(visitNo);
    }

    @Override
    public AlarmVo getUsage() {

        /* 1、查询就诊中患者 */
        String hospitalId = SecurityUtils.getLoginUser().getSysUser().getHospitalId();
        String deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        List<PatVisitUsageVo> patVisitUsageVos = tPatVisitMapper.selectUsageData(hospitalId, deptId);

        AlarmVo alarmVo = new AlarmVo();
        if(patVisitUsageVos.isEmpty()) {
            alarmVo.setNoWearing(Collections.emptyList());
            alarmVo.setNoTemperatureData(Collections.emptyList());
            return alarmVo;
        }

        /* 2、判断监测数据 */
        // 查询的监测数据条数
        int total = 5;
        // 允许间隔时间（毫秒），暂定十分钟
        long interval = 10 * 60 * 1000L;
        // 当前系统时间
        long millis = System.currentTimeMillis();

        // 未佩戴设备的患者
        List<AlarmPatVisitVo> noWearing = new ArrayList<>();
        // 未使用体温传感器的患者
        List<AlarmPatVisitVo> noTemperatureData = new ArrayList<>();
        // 传感器被使用过的患者
        List<AlarmPatVisitVo> sensorUsed = new ArrayList<>();
        // 传感器失效的患者
        List<AlarmPatVisitVo> sensorExp = new ArrayList<>();
        // 传感器不在可使用的地区范围的患者
        List<AlarmPatVisitVo> sensorOutOfArea = new ArrayList<>();
        // 传感器不合法
        List<AlarmPatVisitVo> sensorInvalid = new ArrayList<>();
        for (PatVisitUsageVo info : patVisitUsageVos) {
            Date visitTime = info.getVisitTime();
            PatVisitIntervalData intervalTime = DateUtils.getIntervalTime(visitTime, info.getRentalDays(), null, info.getDataType());

            // 如果已过了就诊起止时间，则跳过
            Date outTime = intervalTime.getOutTime();
            if(outTime.getTime() <= millis) {
                continue ;
            }

            // 查询最新监测记录
            LatestDatasReq req = new LatestDatasReq(info.getEquipmentNo(), visitTime, outTime, total);
            R<List<APISmartBraceletData>> result = remoteTJ02DataService.getLatestDatas(req, SecurityConstants.INNER);
            if (result.getCode() == HttpStatus.SUCCESS) {
                List<APISmartBraceletData> dataList = result.getData();

                // 2.1、优先判断是否正确佩戴设备
                // 2.1.1、如果没有查询到监测数据，且离开单时间过了10分钟，则判断为未佩戴
                if(dataList == null || dataList.isEmpty()) {
                    if(millis - visitTime.getTime() > interval) {
                        AlarmPatVisitVo alarmPatVisitVo = new AlarmPatVisitVo(info.getVisitNo(), info.getPatientId(), info.getPatientName(), info.getBedNo(),"未佩戴设备");
                        noWearing.add(alarmPatVisitVo);
                    }
                    continue ;
                }
                // 2.1.2、如果间隔了十分钟还没数据，说明佩戴有异常
                APISmartBraceletData apiSmartBraceletData = dataList.get(0);
                if(apiSmartBraceletData != null) {
                    Date acquisitionTime = apiSmartBraceletData.getAcquisitionTime();
                    if(acquisitionTime != null && millis - acquisitionTime.getTime() > interval) {
                        AlarmPatVisitVo alarmPatVisitVo = new AlarmPatVisitVo(info.getVisitNo(), info.getPatientId(), info.getPatientName(), info.getBedNo(), "设备佩戴异常");
                        noWearing.add(alarmPatVisitVo);
                        continue ;
                    }
                }
                // 2.1.3、如果得到的数据全是预设值，考虑佩戴异常
                if(dataList.size() == total) {
                    int count = 0;
                    for (int j = 0; j < total; j++) {
                        APISmartBraceletData apiSmartBraceletData1 = dataList.get(j);
                        if(apiSmartBraceletData1 != null
                                && apiSmartBraceletData1.getHeartRate() == EquipmentConstants.INITIAL_HEARTRATE_VALUE
                                && apiSmartBraceletData1.getSpo2() == EquipmentConstants.INITIAL_SPO2_VALUE) {
                            count += 1;
                        }
                    }
                    if(count == total) {
                        AlarmPatVisitVo alarmPatVisitVo = new AlarmPatVisitVo(info.getVisitNo(), info.getPatientId(), info.getPatientName(), info.getBedNo(), "设备未正确佩戴");
                        noWearing.add(alarmPatVisitVo);
                        continue ;
                    }
                }

                // 2.2、再判断体温值是否异常
                // 2.2.1、判断体温传感器是否合法
                if(apiSmartBraceletData != null && SensorConstants.SENSOR_STATUS_ILLEGAL.equals(apiSmartBraceletData.getPlugStatus())) {
                    AlarmPatVisitVo alarmPatVisitVo = new AlarmPatVisitVo(info.getVisitNo(), info.getPatientId(), info.getPatientName(), info.getBedNo(), "体温传感器不合法");
                    sensorInvalid.add(alarmPatVisitVo);
                    continue;
                }

                // 2.2.2、判断传感器是否已被占用
                if(apiSmartBraceletData != null && SensorConstants.SENSOR_STATUS_USED.equals(apiSmartBraceletData.getPlugStatus())) {
                    AlarmPatVisitVo alarmPatVisitVo = new AlarmPatVisitVo(info.getVisitNo(), info.getPatientId(), info.getPatientName(), info.getBedNo(), "体温传感器已被其他患者使用");
                    sensorUsed.add(alarmPatVisitVo);
                    continue;
                }

                // 2.2.3、判断传感器是否已失效
                if(apiSmartBraceletData != null && SensorConstants.SENSOR_STATUS_EXPIRED.equals(apiSmartBraceletData.getPlugStatus())) {
                    AlarmPatVisitVo alarmPatVisitVo = new AlarmPatVisitVo(info.getVisitNo(), info.getPatientId(), info.getPatientName(), info.getBedNo(), "体温传感器已过有效期");
                    sensorExp.add(alarmPatVisitVo);
                    continue;
                }

                // 2.2.4、判断传感器超出规定使用地区
                if(apiSmartBraceletData != null && SensorConstants.SENSOR_STATUS_OUT_OF_AREA.equals(apiSmartBraceletData.getPlugStatus())) {
                    AlarmPatVisitVo alarmPatVisitVo = new AlarmPatVisitVo(info.getVisitNo(), info.getPatientId(), info.getPatientName(), info.getBedNo(), "体温传感器不在可使用的地区范围");
                    sensorOutOfArea.add(alarmPatVisitVo);
                    continue;
                }

                // 2.2.5、判断体温值是否异常
                int count = 0;
                for (APISmartBraceletData data : dataList) {
                    Integer temperature = data.getTemperature();
                    if(temperature == null || temperature == EquipmentConstants.INITIAL_TEMPERATURE_VALUE
                            || temperature == EquipmentConstants.INVALID_TEMPERATURE2 || temperature == 0 || SensorConstants.SENSOR_STATUS_NOT_INSERTED.equals(data.getPlugStatus())) {
                        count += 1;
                    }
                }
                if(count == total) {
                    // 如果都是异常体温，则将患者加入体温异常列表
                    AlarmPatVisitVo alarmPatVisitVo = new AlarmPatVisitVo(info.getVisitNo(), info.getPatientId(), info.getPatientName(), info.getBedNo(), "未正确佩戴体温传感器");
                    noTemperatureData.add(alarmPatVisitVo);
                }
            }
        }

        alarmVo.setNoWearing(noWearing);
        alarmVo.setNoTemperatureData(noTemperatureData);
        alarmVo.setSensorUsed(sensorUsed);
        alarmVo.setSensorExp(sensorExp);
        alarmVo.setSensorInvalid(sensorInvalid);
        alarmVo.setSensorOutOfArea(sensorOutOfArea);
        return alarmVo;
    }

    @Override
    public int doDiagnosis(DiagnosisReq req) {
        TPatVisit patVisit = tPatVisitMapper.selectTPatVisitByVisitNo(req.getVisitNo());
        if (patVisit == null) {
            throw new ServiceException("未查询到该就诊记录");
        }
        String opUserId = SecurityUtils.getUserId();
        if (!opUserId.equals(patVisit.getDoctorId())) {
            throw new ServiceException("只能主治医生操作，您没有权限下诊断！");
        }

        TPatVisit updateInfo = new TPatVisit();
        updateInfo.setVisitNo(req.getVisitNo());
        updateInfo.setDiagnosis(req.getDiagnosis());
        updateInfo.setUpdateBy(SecurityUtils.getUsername());
        updateInfo.setUpdateTime(DateUtils.getNowDate());
        return tPatVisitMapper.updateTPatVisit(updateInfo);
    }

    @Override
    public List<PatVisitHistoryVo> getVisitRecords(VisitRecordReq req) {
        if(req.getStartTime() == null) {
            req.setStartTime(new Date());
        }
        if(req.getEndTime() == null) {
            req.setEndTime(new Date());
        }
        return tPatVisitMapper.selectRecordsByPatient(req.getPatientId(), req.getStartTime(), req.getEndTime(), req.getDataType());
    }

    @Override
    public List<ScreenPatientInfo> listScreenPatient(String hospitalId, String deptId, String keyWord, String dataType) {
        List<PatientDetailInfoVo> patientDetailInfoVos = tPatVisitMapper.selectScreenPatientList(hospitalId, deptId, keyWord, dataType);
        if (patientDetailInfoVos == null || patientDetailInfoVos.isEmpty()) {
            return Collections.emptyList();
        }
        List<ScreenPatientInfo> screenPatientInfoList = new ArrayList<>();
        for (PatientDetailInfoVo patInfo : patientDetailInfoVos) {
            ScreenPatientInfo screenPatientInfo = new ScreenPatientInfo();
            BeanUtils.copyBeanProp(screenPatientInfo, patInfo);
            // 睡眠垫
            if (EquipmentConstants.EQUIPMENT_TYPE_MONITOR_PAD_TYPE.equals(dataType)) {
                //排除同一个人绑定了多台相同设备
                if (screenPatientInfo.getMonitorPadScreenData() != null) {
                    continue;
                }
                screenPatientInfo.setMonitorPadScreenData(getMonitorPadData(patInfo));
            }
            // 多参
            if(EquipmentConstants.EQUIPMENT_TYPE_SMART_BRACELET_TYPE.equals(dataType)) {
                screenPatientInfo.setSmartBraceletScreenData(getSmartBraceletData(patInfo));
            }
            // 心电血压监测仪
            if(EquipmentConstants.EQUIPMENT_TYPE_EB_TYPE.equals(dataType)) {
                screenPatientInfo.setTj03ScreenData(getTj03Data(patInfo));
            }

            screenPatientInfoList.add(screenPatientInfo);
        }
        return screenPatientInfoList;
    }

    /**
     * 获取睡眠垫数据
     * @param patInfo
     */
    private MonitorPadScreenVo getMonitorPadData(PatientDetailInfoVo patInfo){
        String equipmentNo = patInfo.getEquipmentNo();
        PatientEquipmentRTDReq req = new PatientEquipmentRTDReq();
        req.setEquipmentNo(equipmentNo);
        Date visitTime = patInfo.getVisitTime();
        req.setStartTime(visitTime);
        Integer rentalDays = patInfo.getRentalDays();
        PatVisitIntervalData intervalTime = DateUtils.getIntervalTime(visitTime, rentalDays, null, patInfo.getDataType());
        req.setEndTime(intervalTime.getOutTime());

        MonitorPadScreenVo monitorPadScreenVo = new MonitorPadScreenVo();
        //查询床垫的最新数据；
        R<APIMonitorPadData> monitorPadDataResult = remoteTJ01DataService.getLastMonitorPadDataInUse(req, SecurityConstants.INNER);
        if(StringUtils.isNotNull(monitorPadDataResult) && R.FAIL != monitorPadDataResult.getCode()
                && StringUtils.isNotNull(monitorPadDataResult.getData())){
            BeanUtils.copyBeanProp(monitorPadScreenVo, monitorPadDataResult.getData());
        }

        return monitorPadScreenVo;
    }

    /**
     * 获取智能手环数据
     * @param patInfo
     */
    private SmartBraceletScreenVo getSmartBraceletData(PatientDetailInfoVo patInfo){
        PatVisitIntervalData intervalTime = DateUtils.getIntervalTime(patInfo.getVisitTime(), patInfo.getRentalDays(), null, patInfo.getDataType());
        SmartBraceletScreenVo smartBraceletScreenVo = new SmartBraceletScreenVo();

        List<TEquipmentUsageRecords> tEquipmentUsageRecords = equipmentUsageRecordsMapper.selectAllUseRecordByVisitNo(patInfo.getVisitNo());
        // 按开始使用时间倒序排序
        List<TEquipmentUsageRecords> recordsSort = tEquipmentUsageRecords.stream()
                .sorted(Comparator.comparing(TEquipmentUsageRecords::getStartTime).reversed())
                .collect(Collectors.toList());
        for (TEquipmentUsageRecords records : recordsSort) {
            PatientEquipmentRTDReq req = new PatientEquipmentRTDReq();
            req.setEquipmentNo(records.getEquipmentNo());
            req.setStartTime(records.getStartTime());
            req.setEndTime(records.getEndTime() == null || records.getEndTime().after(intervalTime.getOutTime()) ? intervalTime.getOutTime() : records.getEndTime());
            R<APISmartBraceletData> result = remoteTJ02DataService.getLastBraceletDataInUse(req, SecurityConstants.INNER);
            if (result.getCode() == HttpStatus.SUCCESS && result.getData() != null) {
                APISmartBraceletData data = result.getData();
                if(data.getAcquisitionTime() != null) {
                    BeanUtils.copyBeanProp(smartBraceletScreenVo, data);
                    break;
                }
            }
        }

        return smartBraceletScreenVo;
    }

    private TJ03ScreenVo getTj03Data(PatientDetailInfoVo patInfo){
        TJ03ScreenVo tj03ScreenVo = new TJ03ScreenVo();

        List<TEquipmentUsageRecords> tEquipmentUsageRecords = equipmentUsageRecordsMapper.selectAllUseRecordByVisitNo(patInfo.getVisitNo());
        List<RecordsReq> reqList = new ArrayList<>();
        for (TEquipmentUsageRecords records : tEquipmentUsageRecords) {
            RecordsReq req = new RecordsReq();
            req.setVisitNo(patInfo.getVisitNo());
            req.setEquipmentNo(records.getEquipmentNo());
            req.setStartTime(records.getStartTime());
            req.setEndTime(records.getEndTime() == null ? new Date() : records.getEndTime());
            reqList.add(req);
        }

        R<APITJ03RealTimeData> tj03RealTimeData = remoteTJ03DataService.getTj03RealTimeData(reqList, SecurityConstants.INNER);
        if (tj03RealTimeData.getCode() == HttpStatus.SUCCESS && tj03RealTimeData.getData() != null) {
            APITJ03RealTimeData data = tj03RealTimeData.getData();
            if(data.getCreateTime() != null) {
                BeanUtils.copyBeanProp(tj03ScreenVo, data);
            }
        }

        return tj03ScreenVo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult continueBind(Long visitNo) {
        Date nowDate = DateUtils.getNowDate();
        String opName = SecurityUtils.getUsername();
        // 一、先将患者解绑
        // 1.1 就诊状态标记为结束，更新出院时间
        TPatVisit patVisit = tPatVisitMapper.selectTPatVisitByVisitNo(visitNo);
        if (patVisit == null) {
            throw new ServiceException("未查询到患者信息！");
        }
        // 获取预计出院时间
        Date visitTime = patVisit.getVisitTime();
        Integer rentalDays = patVisit.getRentalDays();
        PatVisitIntervalData intervalTime = DateUtils.getIntervalTime(visitTime, rentalDays, null, patVisit.getDataType());
        Date outTime = intervalTime.getOutTime();
        if (nowDate.before(outTime)) {
            // 还未到预计出院时间，将出院时间和新就诊记录的开单时间改为当前时间
            outTime = nowDate;
        }

        patVisit.setVisitStatus(PatVisitStatusConstants.VISIT_STATUS_END);
        patVisit.setOutTime(outTime);
        patVisit.setUpdateBy(opName);
        patVisit.setUpdateTime(nowDate);
        int count = tPatVisitMapper.updateTPatVisitStatus(patVisit);
        if (count < 1) {
            throw new ServiceException("就诊信息标记解绑出错！");
        }

        // 1.2 设备使用记录表标记为未使用
        TEquipmentUsageRecords tEquipmentUsageRecords = equipmentUsageRecordsMapper.selectByVisitNo(visitNo, EquipmentConstants.EQUIPMENT_USE_FLAG_INUSE);
        if (tEquipmentUsageRecords == null) {
            throw new ServiceException("未找到该就诊患者关联的设备使用记录！");
        }
        tEquipmentUsageRecords.setUseFlag(EquipmentConstants.EQUIPMENT_RECORD_STATUS_END);
        tEquipmentUsageRecords.setEndTime(outTime);
        tEquipmentUsageRecords.setUpdateBy(opName);
        tEquipmentUsageRecords.setUpdateTime(nowDate);
        int update = equipmentUsageRecordsMapper.updateTEquipmentUsageRecords(tEquipmentUsageRecords);
        if (update < 1) {
            throw new ServiceException("修改设备使用记录失败！");
        }
        String equipmentId = tEquipmentUsageRecords.getEquipmentId();

        // 二、重新添加新的就诊记录
        // 2.1 添加就诊记录
        long newVisitNo = SnowflakeIdGenerator.getInstance().nextId();
        patVisit.setVisitNo(newVisitNo);
        patVisit.setVisitTime(outTime);
        patVisit.setOutTime(null);
        patVisit.setVisitStatus(PatVisitStatusConstants.VISIT_STATUS_UNDERWAY);
        patVisit.setCreateBy(opName);
        patVisit.setCreateTime(nowDate);
        patVisit.setUpdateBy(opName);
        patVisit.setUpdateTime(nowDate);
        int visitFlag = tPatVisitMapper.insertTPatVisit(patVisit);
        if (visitFlag < 1) {
            throw new ServiceException("患者续绑保存基本信息出错！");
        }

        // 2.2 添加设备使用记录
        tEquipmentUsageRecords.setUseId(null);
        tEquipmentUsageRecords.setVisitNo(newVisitNo);
        tEquipmentUsageRecords.setUseFlag(EquipmentConstants.EQUIPMENT_RECORD_STATUS_INUSE);
        tEquipmentUsageRecords.setStartTime(outTime);
        tEquipmentUsageRecords.setEndTime(null);
        tEquipmentUsageRecords.setUseStatus(EquipmentConstants.SMARTBRACELET_USESTATUS_ABNORMAL);
        tEquipmentUsageRecords.setCreateBy(opName);
        tEquipmentUsageRecords.setCreateTime(nowDate);
        tEquipmentUsageRecords.setUpdateBy(opName);
        tEquipmentUsageRecords.setUpdateTime(nowDate);
        int insert = equipmentUsageRecordsMapper.insertTEquipmentUsageRecords(tEquipmentUsageRecords);
        if (insert < 1) {
            throw new ServiceException("患者续绑分配设备出错！");
        }

        // 2.3 更新医院设备使用状态
        THospitalEquipment tHospitalEquipment = hospitalEquipmentMapper.selectByEquipmentId(equipmentId);
        if (tHospitalEquipment == null) {
            throw new ServiceException("未找到关联的设备信息！");
        }
        // 修改设备使用次数
        // 如果出院时间距离开单时间大于一小时，才减次数
        THospitalEquipment equipment = new THospitalEquipment();
        equipment.setId(tHospitalEquipment.getId());
        equipment.setEquipmentId(equipmentId);
        equipment.setUseFlag(EquipmentConstants.H_EQUIPMENT_USE_FLAG_INUSE);
        equipment.setUpdateBy(opName);
        equipment.setUpdateTime(nowDate);
        if(nowDate.getTime() - visitTime.getTime() > (60 * 60 * 1000)) {
            int days = 0;
            // 获取开单时间到当前出院时间的所有区间日期
            List<Date> allDatesInTheDateRange = DateUtils.getAllDatesInTheDateRange(visitTime, nowDate);
            for (int i = 0; i < allDatesInTheDateRange.size() - 1; i ++) {
                Date start = allDatesInTheDateRange.get(i);
                Date end = allDatesInTheDateRange.get(i + 1);
                long l = end.getTime() - start.getTime();
                if(l > (60 * 60 * 1000)) {
                    days += 1;
                }
            }
            // 实际租用天数
            rentalDays = Math.min(rentalDays, days);

            Integer oldTimes = tHospitalEquipment.getUseTimes();
            equipment.setUseTimes((oldTimes == null ? 0 : oldTimes) + rentalDays);
        }
        int flag = hospitalEquipmentMapper.updateTHospitalEquipment(equipment);
        if (flag < 1) {
            throw new ServiceException("更新设备使用状态失败");
        }

        return AjaxResult.success();
    }
}
